package com.nursinghome.advice;

import com.nursinghome.bean.RespBean;
import com.nursinghome.exception.NurisingHomeException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class WebExceptionHandler {
    //全局异常处理
    @ExceptionHandler(Exception.class)
    public RespBean handleRuntimeException(Exception e){
        e.printStackTrace();
        return RespBean.error("未知错误");
    }
    //自定义异常处理
    @ExceptionHandler(NurisingHomeException.class)
    public RespBean handleRuntimeNurisingHomeException(NurisingHomeException e){
        e.printStackTrace();
        return RespBean.error(e.getMessage());
    }
    //参数验证异常处理
    @ExceptionHandler({BindException.class})
    public RespBean handleMethodArgumentNotValidException(BindException e) {
        BindingResult bindingResult = e.getBindingResult();
        StringBuilder sbf = new StringBuilder("校验失败 ");
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            sbf.append(fieldError.getField()).append("：").append(fieldError.getDefaultMessage()).append(", ");
        }
        String msg = sbf.toString();
        int i = msg.lastIndexOf(", ");
        msg = msg.substring(0, i);
        return RespBean.error(msg);
    }
    //runtime异常处理
    @ExceptionHandler(RuntimeException.class)
    public RespBean runtimeexceptionHandler(RuntimeException e) {
        e.printStackTrace();
        return RespBean.error(e.getMessage());
    }
}
